import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '../router'

export const useUserStore = defineStore('user', () => {
    // 用户token
    const token = ref<string>(localStorage.getItem('token') || '')

    // 用户信息
    const userInfo = ref<any>(null)

    // 设置token
    const setToken = (value: string) => {
        token.value = value
        localStorage.setItem('token', value)
    }

    // 清除token
    const clearToken = () => {
        token.value = ''
        localStorage.removeItem('token')
    }

    // 设置用户信息
    const setUserInfo = (info: any) => {
        userInfo.value = info
    }

    // 清除用户信息
    const clearUserInfo = () => {
        userInfo.value = null
    }

    // 登录
    const login = (loginData: { token: string; userInfo: any }) => {
        setToken(loginData.token)
        setUserInfo(loginData.userInfo)
    }

    // 登出
    const logout = () => {
        clearToken()
        clearUserInfo()
        // 跳转到登录页
        router.push('/login')
    }

    // 检查是否已登录
    const isLoggedIn = () => {
        return !!token.value
    }

    return {
        token,
        userInfo,
        setToken,
        clearToken,
        setUserInfo,
        clearUserInfo,
        login,
        logout,
        isLoggedIn
    }
})